package com.org.oracle.service.impl;

import com.org.oracle.mongodb.dto.DeepSeekDirectRequestDTO;
import com.org.oracle.mongodb.entity.DeepSeekChatRecord;
import com.org.oracle.mongodb.vo.TempChoiceVO;
import com.org.oracle.mongodb.vo.TempDeepSeekNewChatVO;
import com.org.oracle.mongodb.vo.TempUsageVO;
import com.org.oracle.service.DeepSeekChatRepository;
import com.org.oracle.service.DeepSeekChatService;
import com.org.oracle.sub.entity.Message;
import lombok.RequiredArgsConstructor;


import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class DeepSeekChatServiceImpl implements DeepSeekChatService {
    @Autowired
    private final DeepSeekChatRepository chatRepository;
//    private final ChatClient.Builder chatClientBuilder;
    private final ChatClient.Builder chatClientBuilder;
//    private final ChatClient chatClient;
//    @Override
//    public Flux<String> streamChat(String userId, String userInput) {
//        // 初始化包含用户消息的记录
//        DeepSeekChatRecord record = DeepSeekChatRecord.builder()
//                .userId(userId)
//                .messages(new ArrayList<>(List.of(new Message("user", userInput))))
//                .createdAt(LocalDateTime.now())
//                .build();








//        // 保存初始记录并获取ID
//        DeepSeekChatRecord savedRecord = chatRepository.save(record);
//        StringBuilder aiContent = new StringBuilder();
//
//        return chatClientBuilder.build()
//                .prompt()
//                .user(userInput)
//                .stream()
//                .content()
//                .concatMap(content -> {
//                    aiContent.append(content);
//                    return Mono.just(content); // 保持实时流式传输
//                })
//                .doOnComplete(() -> {
//                    // 流结束时添加完整AI消息
//                    savedRecord.getMessages().add(
//                            new Message("assistant", aiContent.toString())
//                    );
//                    chatRepository.save(savedRecord); // 最终持久化
//                });
//    }

    @Override
    public Mono<String> completeChat(String userId, String userInput) {
        // 初始化包含用户消息的记录
        DeepSeekChatRecord record = DeepSeekChatRecord.builder()
                .userId(userId)
                .messages(new ArrayList<>(List.of(new Message("user", userInput))))
                .createdAt(LocalDateTime.now())
                .build();

        // 保存初始记录并获取ID
        return chatRepository.save(record)
                .flatMap(savedRecord ->
                        chatClientBuilder.build()
                                .prompt()
                                .user(userInput)
                                .stream()
                                .content()
                                .reduce(new StringBuilder(), StringBuilder::append)
                                .map(aiContent -> {
                                    // 添加完整AI消息
                                    savedRecord.getMessages().add(
                                            new Message("assistant", aiContent.toString())
                                    );
                                    return savedRecord;
                                })
                )
                .flatMap(chatRepository::save)
                .map(finalRecord -> {
                    // 从最终保存的记录中提取AI回复内容
                    List<Message> messages = finalRecord.getMessages();
                    for (Message message : messages) {
                        if ("assistant".equals(message.getRole())) {
                            return message.getContent();
                        }
                    }
                    return "";
                });
    }

//    @Override
//    public Mono<TempDeepSeekNewChatVO> processDirectRequest(DeepSeekDirectRequestDTO request) {
//        StringJoiner joiner = new StringJoiner(" ");
//        for (Message message : request.getMessages()) {
//            String content = message.getContent();
//            joiner.add(content);
//        }
//        Mono<String> stringMono = completeChat("test01", joiner +",这是一个什么样的概念？");
//
//        return chatClientBuilder.build()
//                .prompt()
//                .messages() // 直接传递消息列表
//                .stream()
//                .content()
//                .collect(Collectors.joining())
//                .map(aiContent -> buildResponse(stringMono.toString(), request.getUserId()))
//                .onErrorResume(e -> Mono.just(buildErrorResponse(e)));
//    }

    @Override
    public Mono<TempDeepSeekNewChatVO> processDirectRequest(DeepSeekDirectRequestDTO request) {
        // 1. 提取所有消息内容（带格式优化）
        String combinedContent = request.getMessages().stream()
                .map(Message::getContent)
                .collect(Collectors.joining("\n"));

        // 2. 调用AI服务（使用实际用户ID）
        return completeChat(request.getUserId(), combinedContent)
                .flatMap(aiContent ->
                        // 3. 构建成功响应
                        Mono.just(buildSuccessResponse(aiContent, request.getUserId()))
                )
                .onErrorResume(e ->
                        // 4. 构建错误响应
                        Mono.just(buildErrorResponse(e))
                );
    }

    // 重构后的响应构建方法
    private TempDeepSeekNewChatVO buildSuccessResponse(String aiContent, String userId) {
        return TempDeepSeekNewChatVO.builder()
                .id(UUID.randomUUID().toString())
                .model("deepseek-r1")
                .usage(TempUsageVO.builder()
                        .promptTokens(100)  // 根据实际情况填写
                        .completionTokens(aiContent.length() / 4) // 模拟token计算
                        .totalTokens(100 + (aiContent.length() / 4))
                        .build())
                .choices(List.of(TempChoiceVO.builder()
                        .message(new Message("assistant", aiContent))
                        .finishReason("stop")
                        .index(0)
                        .build()))
                .build();
    }
    // 专用超时响应构建方法
    private TempDeepSeekNewChatVO buildTimeoutResponse() {
        return TempDeepSeekNewChatVO.builder()
                .id("timeout")
                .model("deepseek-r1")
                .usage(new TempUsageVO())
                .choices(List.of(new TempChoiceVO(
                        new Message("system", "请求处理超时"),
                        "timeout",
                        0
                )))
                .build();
    }
    private TempDeepSeekNewChatVO buildResponse(String aiContent, String userId) {
        return TempDeepSeekNewChatVO.builder()
                .id(UUID.randomUUID().toString())
                .model("deepseek-r1")
                .usage(TempUsageVO.builder()
//                        .prompt_tokens(0)
//                        .completion_tokens(0)
//                        .total_tokens(0)
                        .build())
                .choices(List.of(TempChoiceVO.builder()
                        .message(new Message("assistant", aiContent))
//                        .finish_reason("stop")
                        .index(0)
                        .build()))
                .build();
    }

    private TempDeepSeekNewChatVO buildErrorResponse(Throwable e) {
        return TempDeepSeekNewChatVO.builder()
                .id("error")
                .model("deepseek-r1")
                .usage(TempUsageVO.builder().build())
                .choices(List.of(TempChoiceVO.builder()
                        .message(new Message("system", "服务异常: " + e.getMessage()))
//                        .finish_reason("error")
                        .index(0)
                        .build()))
                .build();
    }

//    @Override
//    public Flux<DeepSeekChatRecord> getChatHistory(String userId) {
//        return chatRepository.findByUserIdOrderByCreatedAtDesc(userId);
//    }
}
